/**
 * Created by shugen on 2017/2/11.
 */



var max=0;
var flag=true;
//  提交答案
$("#submit").click(function(){
    flag=true;
    if(max>0){ toastAlert("error","提交失败","只能提交一次！"); return ;}
    var list=$("#questionlist").find("article");
    var results=[];
    list.each(function(i,o){
        results.push(toresult(o));
        if(!flag) return false ;  //break;
    });
    if(flag) {

        var anserkey = {};
        anserkey.qid = $("#init").data("id");
        anserkey.anserList = results;
        try {
            anserkey = JSON.stringify(anserkey);
          //  console.info(anserkey);
            $.post($("#path").val() + "/Question/returnAnser", {
                anserkey: anserkey,
            }, function (data) {
                max++;
                data=JSON.parse(data);
                toastAlert(data.state,data.opera,data.msg);
            });
        } catch (err){
            console.info("异常");
        }
    }

});

function  creakQuestion(result){
   // console.info(result);
    $("#title").text(result.title);
    $("#summary").text(result.summary);
    $("#init").data("id",result.id);
    if(!result.start){$("#title").text(result.title+"---(该问卷已停用)");  $("#submit").remove();}
     var list=$("#questionlist");
    $.each(result.questions,function(i,o){
        //单选
        var clas="formwidget col50";
        if(o.type=="1") clas=" formwidget radio col100";
        else if(o.type=="2") clas=" formwidget checkboxlist col100";
        else if(o.type=="7") clas=" formwidget  col75";
        var article=$("<article otype='"+o.type+"' order='"+o.order+"' class='"+clas+"'></article>");
        article.append(creatArticleBody(o));

        list.append(article);
    });

}
function createResult(result2){
    $("#submit").remove();
    $("title").text("答案回填");
  //  console.info(result2);
    $("#title").text($("#title").text()+"("+result2.ctimeToFullString+" 填写)");
    var anserList=result2.anserList;
    var list=$("#questionlist").find("article");
    //回填
    $.each(anserList,function (i,o) {
        var li=    $(list[o.qorder-1]);
        //单选回填
        if(li.attr("otype")=="1"){
            var val=o.result.substring(2,o.result.length-2);
            $("input[name='order"+o.qorder+"'][value='"+val+"']").click();
        }
        else if(li.attr("otype")=="2"){
            var val=eval(o.result);
            $.each(val,function(i,c){
                $("input[name='order"+o.qorder+"'][value='"+c+"']").click();
            });
        }
        else if(li.attr("otype")=="5"||li.attr("otype")=="6"){
            var val=eval(o.result);
            $.each(val,function(i,c){
                $($("input[name='order"+o.qorder+"']")[0]).val(c);
            });
        }

        else if(li.attr("otype")=="7"){
            var val=eval(o.result);
            $.each(val,function(i,c){
                $("textarea[name='order"+o.qorder+"']").text(c)
            });
        }

    });

    $("input,textarea").each(function(i,e){
        $(e).attr("disabled","disabled");
    })

}

// 提示框事件
function toastAlert(icon,heading,text){
    $.toast({
        heading: heading,
        text: text,
        stack: false,
        position: 'mid-center',
        showHideTransition: 'fade',
        icon: icon   // icon:error warning  success info
    })
}

function creatArticleBody(o){
var body="<header><h4>"+o.order+"."+o.title+"("+o.typeTo+")"+"</h4></header>"+
    "<div  class='widgetbody'> <div class='formfield'> <div class='fieldbody'>"
    if(o.type=="1"||o.type=="2"){
        var contexts=(o.context).substring(2,o.context.length-2);
        contexts=eval(contexts);//  解析 数组
        var i=1;
        var  radio="";
        var type="radio" ,clas="left";
        if(o.type=="2"){type="checkbox";clas=""};

        $.each(contexts,function(j,c){
            radio+="<div class='fieldchoice "+clas+"'><input type='"+type+"' name='"+"order"+o.order+"' value='"+(i++)+"'  class='field"+type+"'/> <label class='choicetext' >"+c+"</label></div>"

        });
        body+=radio;
    }//   单选 多选
    else {
        var contexts=o.context.substring(4,o.context.length-4);
        if(o.type=="5"){

            var contexts=replace2(contexts,"()"," <input type='text' name='"+"order"+o.order+"'  class='fieldinput clo25' style='height: 30px;max-width: 180px;'/> ");
            contexts=replace2(contexts,"（）"," <input type='text' name='"+"order"+o.order+"'  class='fieldinput clo25' style='height: 30px;max-width: 180px;'/> ");
            body+=contexts;
        }
        else if(o.type=="6"){
            var contexts=replace2(contexts,"[]"," <input type='text' name='"+"order"+o.order+"'  class='fieldinput clo25' style='height: 30px;max-width: 180px;'/> ");
            contexts=replace2(contexts,"【】"," <input type='text' name='"+"order"+o.order+"'  class='fieldinput clo25' style='height: 30px;max-width: 180px;'/> ");
            body+=contexts;
        }
        else {
            contexts="<textarea name='"+"order"+o.order+"' class='fieldtextarea'>"+contexts+"</textarea>"
            body+=contexts;
        }
    }
body+="</div></div></div>";
    return body;
}

function replace2(str,sub,re){
    var o;
    var j=0;
    for(;;){
        j++;
        o=str
        str=str.replace(sub,re);
        if(str==o||j>30) break;
    }
    return str;
}
function toresult(li){
    var  anser= {};
    var result=[];
    var qorder=$(li).attr("order");
    var qorderstr="order"+qorder;
    //单选
    if($(li).attr("otype")=="1"){
        $(':radio[name='+qorderstr+']:checked').each(function(){
            result.push($(this).val());
        });
    }
    else if($(li).attr("otype")=="2"){
        $(':checkbox[name='+qorderstr+']:checked').each(function(){
            result.push($(this).val());
        });
    }
    else if($(li).attr("otype")=="5"||$(li).attr("otype")=="6"){
        result=[];
        $('[name='+qorderstr+']').each(function(){
            result.push($(this).val());
        });
    }
    else if($(li).attr("otype")=="7"){
        result.push($('[name='+qorderstr+']').val());
    }
    if((result.toString()==""||result.toString()==null)&&$(li).attr("otype")!="7"&&$('[name='+qorderstr+']').length!=0){
        toastAlert("error","第"+qorder+"题未答","不允许提交!"); flag=false;  return ;
    }
    anser.qorder=qorder;
    anser.result=result;
    return anser;
}

